package com.wgtp.ssapp.model.tasks;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.wgtp.ssapp.R;
import com.wgtp.ssapp.view.activity.LoginActivity;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class GetForumListTask extends AsyncTask<String, Integer, Boolean> {

	private String TAG = "GetForumListTask";
	private ProgressDialog dialog;
	private LoginActivity activity;
	private Boolean gotForums, isTaskDone;
	private String mainHTML;
	
	public GetForumListTask(LoginActivity activity) {
		dialog = new ProgressDialog(activity);
		gotForums = false;
		isTaskDone = false;
		mainHTML = "";
		this.activity = activity;
	}
	
	@Override
	protected void onPreExecute() {
		Log.i(TAG, "starting onPreExecute");
	}
	
	@Override
	protected void onPostExecute(Boolean bool) {
		Log.i(TAG, "starting onPostExecute");
		
		if(dialog.isShowing())
			dialog.dismiss();
	}
		
	@Override
	protected Boolean doInBackground(String... params) {
		Log.i(TAG, "starting doInBackground");
		
		boolean rtn = false;
		try {
	    	HttpClient httpClient = new DefaultHttpClient();
	        HttpGet httpGet = new HttpGet(activity.getString(R.string.main_url));
	        HttpResponse response = httpClient.execute(httpGet);
	        HttpEntity httpEntity = response.getEntity();
	        mainHTML = EntityUtils.toString(httpEntity);
	        
	        Log.i(TAG, "got main html successfully");
	        gotForums = true;
			isTaskDone = true;
	        return true;
    	}
    	catch(IOException e) {
    		Log.e(TAG, "getting main forum html failed, " + e.getStackTrace().toString(), e);
    		return false;
    	}
	}
	
	public boolean didGetForums() {
		return gotForums;
	}
	
	public boolean isTaskDone() {
		return isTaskDone;
	}
	
	public String getMainHTML() {
		return mainHTML;
	}
}
